//销售结算 详情页面↓
<template>
  <!-- 集采汇总编辑页 -->
  <div class="e-form">
      <BillTop @cancel="handleClose"></BillTop>
    <!-- //详情 添加页面 ↓ -->
    <div class="tabs">
      <el-tabs tab-position="left" v-model="tabsName" @tab-click="onChangeTab">
        <!-- 基本信息 -->
        <el-tab-pane
          label="基本信息"
          name="baseInfo"
          :disabled="clickTabFlag"
        ></el-tab-pane>

        <el-tab-pane
          label="结算明细"
          name="planDetail"
          :disabled="clickTabFlag"
        ></el-tab-pane>

        <!-- <el-tab-pane
          label="服务费用"
          name="fwfy"
          :disabled="clickTabFlag"
        ></el-tab-pane>

        <el-tab-pane
          label="保证金"
          name="bzj"
          :disabled="clickTabFlag"
        ></el-tab-pane> -->

        <el-tab-pane
          label="附件信息"
          name="accessory"
          :disabled="clickTabFlag"
        ></el-tab-pane>

        <el-tab-pane
          label="审核历史"
          name="auditHistory"
          :disabled="clickTabFlag"
        ></el-tab-pane>

        <!-- <el-tab-pane
          label="审核历史"
          name="auditHistory"
          :disabled="clickTabFlag"
        ></el-tab-pane> -->
        <div>
          <!-- 基本信息 -->
          <div id="baseInfoCon" class="con">
            <div class="e-form">
              <div class="tabs">
                <div class="tabs-title" id="baseInfo">基本信息</div>
                <div style="width: 100%" class="form">
                     <el-form ref="rulesBase" :model="formData" label-width="150px"  :rules="rulesBase" class="demo-ruleForm">
                                    <el-row>
                                        <el-col :span="12">
                                            <el-form-item label="结算编号：" prop="billNo">
                                                <span>{{formData.billNo}}</span>
                                                <!-- <el-input v-model="formData.billNo"></el-input> -->
                                            </el-form-item>
                                        </el-col>
                                        <el-col :span="12">
                                            <el-form-item label="机构：" prop="orgName">
                                                <span>{{formData.orgName}}</span>
                                                <!-- <el-input v-model="formData.orgName"></el-input> -->
                                            </el-form-item>
                                        </el-col>
                                    </el-row>
                                    <el-row>
                                        <el-col :span="12">
                                            <el-form-item label="客户单位：" prop="customerName">
                                                <el-input :disabled="true" v-model="formData.customerName"></el-input>
                                                <el-button @click="xzxsgt"
                                                 type="primary"
                                                 class="btn-blue"
                                                >选择销售合同</el-button>
                                            </el-form-item>
                                        </el-col>
                                        <el-col :span="12">
                                            <el-form-item label="源单编号：">
                                                <span>{{formData.contractName}}</span>
                                                <span class="a"
                                                @click="goTocontract">查看</span>
                                            </el-form-item>
                                        </el-col>
                                    </el-row>
                                    <el-row>
                                        <el-col :span="12">
                                            <el-form-item label="销售金额(元)：">
                                               <!-- <span>{{formData.amount}}</span> -->
                                               <span>{{xiaoshoujine}}</span>
                                            </el-form-item>
                                        </el-col>
                                        <el-col :span="12">
                                            <el-form-item label="结算日期：">
                                                 <el-date-picker v-model="formData.settlementDate" type="date" placeholder="选择日期" :clearable="false"
                                                 value-format="yyyy-MM-dd"
                                                        format="yyyy 年 MM 月 dd 日">
                                                </el-date-picker>
                                            </el-form-item>
                                        </el-col>
                                    </el-row>
                                    <el-row>
                                        <el-col :span="12">
                                            <el-form-item label="税率%：">
                                                <el-input v-model="formData.taxRate" type="number"
                                                @change="taxRateEvent"
                                                ></el-input>
                                            </el-form-item>
                                        </el-col>
                                        <el-col :span="12">
                                            <!-- 返回id、名字 -->
                                            <el-form-item label="销售人员：" prop="salesman">
                                                <span>{{formData.salesman}}</span>
                                                <!-- <el-input v-model="formData.salesman"></el-input> -->
                                            </el-form-item>
                                        </el-col>
                                    </el-row>
                                    <el-row>
                                        <el-col :span="12">
                                            <el-form-item label="税额：">
                                                <el-input v-model="formData.taxAmount"
                                                @change="taxAmountEvent"
                                                type="number"></el-input>
                                            </el-form-item>
                                        </el-col>
                                        <el-col :span="12">
                                            <el-form-item label="税价合计：">
                                                <!-- formData.rmbTotalAmount -->
                                                <span>{{formData.totalAmount}}</span>
                                            </el-form-item>
                                        </el-col>
                                    </el-row>

                                    <el-row>
                                        <el-col :span="12">
                                            <el-form-item label="本位币：" prop="baseCurName">
                                                <span>{{formData.baseCurName}}</span>
                                               <!-- <el-input v-model="formData.baseCurName"></el-input> -->
                                            </el-form-item>
                                        </el-col>
                                        <el-col :span="12">
                                            <el-form-item label="币种：">
                                               <span>{{formData.currency}}</span>
                                            </el-form-item>
                                        </el-col>
                                    </el-row>

                                      <el-row>
                                        <!-- <el-col :span="12">
                                            <el-form-item label="传财务共享(暂时没得)：">
                                                <span>{{formData.cwgx}}</span>
                                            </el-form-item>
                                        </el-col> -->
                                        <!-- <el-col :span="12">
                                            <el-form-item label="销售金额(本位币)：">
                                                <span>{{xiaoshoujine}}</span>
                                            </el-form-item>
                                        </el-col> -->
                                        <el-col :span="12">
                                            <el-form-item label="状态：" prop="state">
                                                <span>{{  state.find(x=>x.value == formData.state).label  }}</span>
                                                <!-- <span>{{formData.baseCurAmount}}</span> -->
                                            </el-form-item>
                                        </el-col>
                                    </el-row>

                                    <!-- <el-row>
                                        <el-col :span="12">
                                            <el-form-item label="状态：">
                                                <span>{{formData.state}}</span>
                                            </el-form-item>
                                        </el-col>
                                    </el-row> -->

                                      <el-row>
                                        <el-col :span="24">
                                            <el-form-item label="备注：">
                                               <el-input type="textarea" :rows="2" laceholder="请输入内容" v-model="formData.remarks"></el-input>
                                            </el-form-item>
                                        </el-col>
                                    </el-row>

                                </el-form>
                </div>
              </div>
            </div>
          </div>
          <!-- 结算明细 -->
          <div id="planDetailCon" class="con">
            <div class="tabs-title" id="planDetail">结算明细</div>
            <!-- {{webData}} -->
            <div class="e-tree-table">
                    <div class="top">
                      <div class="left">
                        <div>
                          <el-button
                            size="small"
                            style="background: rgb(75, 178, 255); color: #fff"
                            @click="xzxsgt"
                            >新增</el-button
                          >
                        </div>
                      </div>
                    </div>
                    <el-table
                        :header-cell-style="{ textAlign: 'center' }"
                        :cell-style="{ textAlign: 'center' }"
                        :data="wzlbTableData"
                        ref="wzlbTableDataTable"
                        border
                        style="width: 100%; "
                        :row-class-name="tableRowClassName"
                        :cell-class-name="cellClsNm"
                        :tree-props="{
                            children: 'children',
                            hasChildren: 'hasChildren',
                        }"
                        default-expand-all
                        row-key="uuid"
                        v-sortTable="{ 'tableData': wzlbTableData, '_this': this, 'ref': 'wzlbTableDataTable' }"
                    >
                    <el-table-column prop="itemName" label="操作" width="100" fixed>
                        <template slot-scope="{ row }">
                            <div style="display:flex; justify-content: flex-start; width: 100%;" v-if='!row.children'>
                                <img src="@/assets/btn/delete.png" class="cancel_delete" title="删除" @click="deleteEle(row)">
                            </div>
                        </template>
                    </el-table-column>
                      <el-table-column prop="topClassName" label="物资类别" width="150">
                      </el-table-column>
                      <el-table-column prop="materialName" label="物资名称" >
                      </el-table-column>
                      <el-table-column prop="spec" label="规格" width="200">
                      </el-table-column>
                      <el-table-column prop="texture" label="材质" width="200">
                      </el-table-column>
                      <el-table-column prop="unit" label="计量单位" width="100">
                      </el-table-column>
                      <el-table-column prop="warehouseName" label="仓库" width="200">
                      </el-table-column>
                      <el-table-column prop="unsettledQuantity" label="未结算数量" width="150">
                      </el-table-column>
                      <el-table-column prop="settlementUnit" label="结算数量" width="150">
                           <template slot-scope="{ row }">
                                <el-input v-if="row.billId || row.billId == ''" :max="row.unsettledQuantity" v-model="row.settlementUnit" type="number" @change="gaibian(row,'数量')"></el-input>
                            </template>
                      </el-table-column>
                       <el-table-column

                        prop="price"
                        label="单价(元)"
                        width="150"
                      >
                      </el-table-column>
                      <!-- prop="amount" -->
                       <el-table-column  label="金额(元)" width="150">
                           <template slot-scope="{ row }">
                                <el-input v-if="row.billId || row.billId == ''" v-model="row.amount" type="number" @change="gaibian(row,'金额')"></el-input>
                            </template>
                        </el-table-column>
                    </el-table>
                  </div>
          </div>

          <!-- 附件信息 -->
          <div id="accessoryCon" class="con">
            <div class="tabs-title" id="accessory">附件信息</div>
            <attach-comp
              :relationId="attachId"
              bucketName="turnover"
            />
          </div>

          <!-- 审核历史 -->
          <div id="auditHistoryCon" class="con">
            <div class="tabs-title" id="auditHistory">审核历史</div>
            <div class="e-table">
            <div class="e-table">
                <ComAuditHistoryIndex :billType="1021" :tableData.sync="shenheArr" @getAuditHistory="getauditHistory"   ref="AuditHistoryRef"/>
            </div>
            </div>
          </div>

        </div>
      </el-tabs>
    </div>
    <div id="seat" :style="{ height: seatHeight + 'px' }"></div>
           <div class="buttons">
            <span class="tip"><span style="color: red; margin-right: 0">*</span>为必填项</span>
            <exaButtons :auditState="auditState" @exas="exas" :state="formData.state - 0" :founderId="formData.founderId" ></exaButtons>
            <el-button size="small" @click="handleClose">取消</el-button>
        </div>
  </div>
</template>

<script>
import '@/utils/jquery.scrollTo.min'
import { mapMutations, mapState } from 'vuex'
import { showSuccessPop, getUuid } from '@/utils/common'
import AttachComp from '@/components/common/attachIndex'
import planRequest from '@/api/turnover/plan.js'
import { selectDataClient, openAppClient } from '@/utils/common'
import auditRequest from '@/api/materialSettlement/salesSettlement.js'
import ComAuditHistoryIndex from '@/pages/materialsmanagement/components/auditHistory/auditHistoryIndex'
import publicReques from '@/api/materialSettlement/public.js'
import { showErrorPop } from '@/utils/common'
import exaButtons from '@/components/common/exaButtons'
export default {
    components: {
        AttachComp,
        ComAuditHistoryIndex,
        exaButtons
        // historyUpdateTable
    },
    data () {
        return {
            //我的数据:↓
            // shenheArr: [],
            webData: '',
            formData: {
                billNo: '', //结算单号
                orgName: '', //机构名称
                orgId: '', //机构id
                customerName: '', //客户单位
                customerId: '', //客户id
                contractName: '', //合同名称
                contractBillNo: '', //合同编号
                contractBillId: '', //合同id
                amount: 100, //销售金额 元
                settlementDate: '', //结算日期
                taxRate: 0, //税率
                salesman: '', //销售人员
                rmbTaxAmount: 0, //税额
                rmbTotalAmount: 0, //税价合计
                baseCurName: '', //本位币名称
                baseCurId: '', //本位币id
                baseCurRate: 0, //本位币汇率
                currency: '', //币种名称
                currencyId: '', //币种id
                cwgx: '', //传财务共享 需要改字段
                baseCurAmount: 0, //销售金额(本位币)
                state: '0', //状态
                remarks: ''//备注
            },
            rulesBase: {
                billNo: [
                    { required: true, message: '结算编号不能为空', trigger: 'change' }
                ],
                orgName: [
                    { required: true, message: '机构不能为空', trigger: 'change' }
                ],
                settlementDate: [
                    { required: true, message: '结算日期不能为空', trigger: 'change' }
                ],
                customerName: [
                    { required: true, message: '客户单位不能为空', trigger: 'change' }
                ],
                salesman: [
                    { required: true, message: '销售人员不能为空', trigger: 'change' }
                ],
                baseCurName: [
                    { required: true, message: '本位币不能为空,请选择销售合同', trigger: 'change' }
                ],
                state: [
                    { required: true, message: '状态不能为空', trigger: 'change' }
                ],

            },
            nullifyParams: {
                // 作废
                billId: this.$route.query.billid,
                billType: '1021',
                nullifyDescription: '',
                nullifyReason: true,
                nullifyCreated: '',
                nullifyCreator: '',
                nullifyCreatorId: ''
            },
            typeArr: [
                { name: '草稿', id: 0 },
                { name: '审核中', id: 1 },
                { name: '共享审核中', id: 9 },
                { name: '已审核', id: 2 },
                { name: '已关闭', id: -1 },
                { name: '已作废', id: 5 },
            ],
            viewList: true,
            paginationInfo: {
                total: 1,
                pageSize: 10,
                currentPage: 0
            },
            query: {
                beginPlanDate: '',
                endPlanDate: '',
                keyword: '',
                limit: 0,
                orgId: '',
                page: 1,
                settlementUnitId: '',
                states: []
            }, //搜索
            searchKey: '', //右上角搜索关键字
            tableData: [], //表格
            shenheArr: [],
            wzlbTableData: [],
            //我的数据:↑

            auditState: {},
            auditParams: {
                billId: this.$route.query.billid,
                billType: 6087,
                freeNextUnitIndex: 0,
                freeNextUser: '',
                isPass: true,
                isShareInAudit: true,
                opinion: ''
            },
            tabsName: 'baseInfo',
            userName: '',
            clickId: 'baseInfo',
            tabsNameChild: '',
            childTabClass: '',
            form: {
                name: '',
                region: '',
                date1: '',
                date2: '',
                delivery: false,
                type: [],
                resource: '',
                desc: '',
            },
            OrgtableData: [], //申报机构数据
            OrgSonTableData: [], //申报机构子列表
            materialsTableData: [], //物资汇总数据
            auditHistoryList: [], //审核历史
            planSelect: [], //申报机构表格明细选择项
            value: '',
            textarea: '',
            screenWidth: 0,
            screenHeight: 0,
            lastConHeight: 0,
            MouseEnterId: 0,
            clickTabFlag: false, // 如果手动点击时，则不做滚动事件逻辑，只有滚动屏幕时才走滚动事件逻辑
            //基本信息表单数据
            basicFormData: {
                'amount': null,
                'billId': '',
                'billNo': '',
                'founderId': '',
                'founderName': '',
                'gmtCreate': '',
                'gmtModified': '',
                'nullifyCreated': '',
                'nullifyCreator': '',
                'nullifyCreatorId': '',
                'nullifyDescription': '',
                'nullifyReason': '',
                'operator': '',
                'operatorId': '',
                'orgId': '',
                'orgName': '',
                'remarks': '',
                'sourceBillId': '',
                'sourceBillNo': '',
                'sourceType': null,
                'state': '',
                'summaryDate': '',
                'workId': ''
            },
            objFlag: {
                flag5: false,
            },
            orgId: '', //机构id
            orgName: '', //机构名称
            billId: '',
            isSkip: false, //是否跳转
            show: true, //申报机构子列表
            dtlIds: '', //
            //验证
            rules: {
                summaryDate: [
                    { required: true, message: '请输入汇总日期', trigger: 'blur' },
                ],
                currencyId: [
                    { required: true, message: '请选择币种', trigger: 'chenge' },
                ],
            },
            materialsNameData: [], //机构汇总表
            createHistoryData: [], //明细修改历史列表
            errorMsg: [],
            isErrorMsg: true, //是否提醒错误信息
            warehouse: {} //登陆人机构下的仓库名称

        }
    },
    async created () {
        this.user = JSON.parse(localStorage.getItem('vuex'))
        this.billId = this.$route.query.billid
        this.auditState = await publicReques.getCurrentUnitInfo({
            billId: this.$route.query.billid,
            billType: '1021'
        })
        console.log('333', this.auditState)
        const data = await auditRequest.getxsjsbyid({ id: this.billId })
        console.log(data, 'data')
        this.formData = data
        let list = await auditRequest.getjsmxbyid({ id: this.billId })
        // this.setSelectedInfo(list)
        // // // 客户端弹窗预览结果
        // // // 参数依次为: 打开页面地址、标题、回调函数
        // openAppClient('/showSelectedData', '选择结果', function () {
        //     // alert('关闭后回调')
        // })
        for(let i = 0 ; i < list.length ; i++) {
            list[i].uuid = getUuid()
            for(let j = 0 ; j < list[i].children.length ; j++) {
                list[i].children[j].uuid = getUuid()
                list[i].children[j].settlementUnit = list[i].children[j].quantity
            }
        }
        this.wzlbTableData = list
        console.log(list)
        this.getProjectDepartmentWarehouse()
        // let data = JSON.parse(localStorage.getItem('vuex'))
        // this.orgId = data.userInfo.orgInfo.orgId
        // this.orgName = data.userInfo.orgInfo.orgName
        // this.userId = localStorage.getItem('userId')
        // this.basicFormData.operator = localStorage.getItem('userName')
        // this.billId = this.$route.query.billid

        // this.initData()
    },
    watch: {
    },
    computed: {
        ...mapState({
            options: state => state.contract.ctClassify,
            popConfirm: 'popConfirm',
            popStatus: 'popStatus',
            userInfo: state => state.userInfo,
            currencyForm: state => state.equip.equipData.currencyForm, //币种
            state: state => state.equip.equipData.state, //通用流程状态
        }),
        xiaoshoujine () {
            if(this.wzlbTableData.length == 0) {
                return 0
            }else{
                let num = 0
                for(let i = 0 ; i < this.wzlbTableData.length ; i++) {
                    if( this.wzlbTableData[i].children.length > 0) {
                        for(let j = 0 ; j < this.wzlbTableData[i].children.length ; j++) {
                            num += this.wzlbTableData[i].children[j].amount
                        }
                    }else{
                        num + 0
                    }
                }
                return num - 0
            }

        },
        // 填补底部空白，以使高度够滚动
        seatHeight () {
            return this.screenHeight - 72 - this.lastConHeight
        },
        attachId () {
            return this.billId
        },
    },

    mounted () {
    // 获取最后一个内容区域的高度，计算底部空白
        this.getLastConHeight()

        // 保存所有tabName
        const arr = [
            'baseInfo',
            'planDetail',
            'accessory',
            'auditHistory',
        ]
        let $idsTop = []
        window.addEventListener('scroll', () => {
            // 如果手动点击时，则不做滚动事件逻辑，只有滚动屏幕时才走滚动事件逻辑
            //当点击的tab有子tab时做滚动逻辑
            if (this.clickTabFlag && arr.find(x => x === this.clickId)) {
                this.childTabClass = '' //无子tab时清空tab的类名
                return
            }

            if (!$idsTop[$idsTop.length - 1]) {
                $idsTop = arr.map(item => {
                    let itemTop
                    let arr
                    if (item instanceof Array) {
                        const prevHeight = document.getElementById(item[0]).offsetHeight //因这里一个选项有两个表格，需获取前一个表格的高度进行计算
                        arr = item.map((x, i) => {
                            if (i === 0) {
                                return document.getElementById(x).offsetTop
                            } else {
                                return (
                                    document.getElementById(x).offsetTop +
                  prevHeight +
                  document.getElementById(item[0]).offsetTop
                                )
                            }
                        })
                        return arr
                    } else {
                        itemTop = document.getElementById(item).offsetTop
                        return itemTop
                    }
                })
            }
            const scrollTop =
        document.documentElement.scrollTop || document.body.scrollTop
            // 倒序查找
            let curLocal = 0
            let curLocalChild = 1
            for (let len = $idsTop.length, i = len - 1; i >= 0; i--) {
                if ($idsTop[i] instanceof Array) {
                    let item = $idsTop[i]
                    for (let lenth = item.length, j = lenth - 1; j >= 1; j--) {
                        let itemChild = $idsTop[i][j]
                        if (scrollTop + 1 >= itemChild) {
                            curLocalChild = j
                            break
                        }
                    }
                    if (scrollTop + 1 >= item[0]) {
                        curLocal = i
                        break
                    }
                } else {
                    let item = $idsTop[i]
                    if (scrollTop + 1 >= item) {
                        curLocal = i
                        break
                    }
                }
            }
            // 设置对应tabName
            if (arr[curLocal] instanceof Array) {
                this.tabsName = arr[curLocal][0]
                this.tabsNameChild = arr[curLocal][curLocalChild]
            } else {
                this.tabsName = arr[curLocal]
            }
            // //动态改变二级选项卡类名
            // arr.forEach((item, index) => {
            //     if (item instanceof Array) {
            //         let tabNavHeight = document.querySelector('.childTab .el-tabs__nav')
            //             ? document.querySelector('.childTab .el-tabs__nav').offsetHeight
            //             : 0
            //         if (scrollTop + 1 >= $idsTop[index + 1] - tabNavHeight) {
            //             this.childTabClass = 'childTab2'
            //         } else if (scrollTop <= $idsTop[index][1]) {
            //             this.childTabClass = ''
            //         } else {
            //             this.childTabClass = 'childTab1'
            //         }
            //     }
            // })
        })

        this.screenWidth = document.documentElement.clientWidth - this.topHeight
        this.screenHeight = document.documentElement.clientHeight - this.topHeight
        window.addEventListener('resize', () => {
            this.screenWidth = document.documentElement.clientWidth - this.topHeight
            this.screenHeight = document.documentElement.clientHeight - this.topHeight
            $idsTop = arr.map(item => {
                let itemTop
                let arr
                if (item instanceof Array) {
                    const prevHeight = document.getElementById(item[0]).offsetHeight //因这里一个选项有两个表格，需获取前一个表格的高度进行计算
                    arr = item.map((x, i) => {
                        if (i === 0) {
                            return document.getElementById(x).offsetTop
                        } else {
                            return (
                                document.getElementById(x).offsetTop +
                prevHeight +
                document.getElementById(item[0]).offsetTop
                            )
                        }
                    })
                    return arr
                } else {
                    itemTop = document.getElementById(item).offsetTop
                    return itemTop
                }
            })
        })
    },
    methods: {
        ...mapMutations(['setPopConfirm', 'setSelectedInfo', 'setHistoryTableData']),

        //我的方法 ↓
        async exas (arg) {
            if (arg === 'submit') {
                console.log('1') // 保存所有数据
                await this.thesubmit()
            } else if (arg === 'submitCommit') {
                console.log('2') // 保存并提交
                await this.submitCommit()
            } else if (arg === 'audit') {
                console.log('3') // 审核
                await this.shenhe()
            } else if (arg === 'undoAudit') {
                await this.nullify() // 撤销审核
            } else if (arg === 'nullify') {
                console.log('5') // 作废(
                await this.zuofei()
            } else if (arg === 'deleteData') {
                console.log('6') // 删除
                await this.shanchu1()
            }
        },
        async shanchu1 () {
            this.clientPop('info', '确认删除这条数据吗？此操作不可逆转!', async ()=>{
                await auditRequest.deltexsjs({ id: this.$route.query.billid })
                this.clientPop('suc', '删除成功' )
                this.$router.replace('/salesSettlementlist')
            })

            // await auditRequest.deltexsjs({ id: this.billId })
            // this.clientPop('suc', '删除成功')
            // this.$router.replace('/salesSettlementlist')
        },

        //审核历史
        async getauditHistory () {
            if(this.billId !== '') {
                const data = await publicReques.getauditHistory({
                    'billId': this.billId,
                    'billType': 1021,
                    'freeNextUnitIndex': 0,
                    'freeNextUser': '',
                    'isPass': true,
                    'isShareInAudit': true,
                    'opinion': ''
                })
                // this.shenheArr = []
                this.shenheArr = data
            }
        },
        shenhe () {
            console.log('审核')
            openAppClient('/exaDialog', '填写审核意见',  ()=> {
                const auditParams = JSON.parse(localStorage.vuex).auditParams
                // 将审核意见赋值给参数传给后端
                publicReques.goaudit({
                    billId: this.billId,
                    billType: '1021',
                    isPass: auditParams.isPass,
                    isShareInAudit: false,
                    opinion: auditParams.opinion

                }).then(() => {
                    this.clientPop('suc', '审核成功')
                    this.$router.replace('/salesSettlementlist')
                }).catch(()=>{
                    this.clientPop('suc', '审核失败')
                })

            })
        },
        thesubmit () {
            this.$refs.rulesBase.validate(valid => {
                console.log('gg', valid)
                if (valid) {
                    this.thesubb()
                } else {
                    console.log('error submit!!')
                    return false
                }
            })
        },
        async thesubb () {
            //点击保存
            //  billNo: '', //结算单号
            //     orgName: '', //机构名称
            //     orgId: '', //机构id
            //     customerName: '', //客户单位
            //     customerId: '', //客户id
            //     contractName: '', //合同名称
            //     contractBillNo: '', //合同编号
            //     contractBillId: '', //合同id
            //     amount: 0, //销售金额 元
            //     settlementDate: '', //结算日期
            //     taxRate: 0, //税率
            //     salesman: '', //销售人员
            //     rmbTaxAmount: 0, //税额
            //     rmbTotalAmount: 0, //税价合计
            //     baseCurName: '', //本位币名称
            //     baseCurId: '', //本位币id
            //     baseCurRate: 0, //本位币汇率
            //     currency: '', //币种名称
            //     currencyId: '', //币种id
            //     cwgx: '', //传财务共享 需要改字段
            //     baseCurAmount: 0, //销售金额(本位币)
            //     state: '0', //状态
            //     remarks: ''//备注

            //点击详情进来的 rmbTaxAmount
            this.$set(this.formData, 'amount', this.xiaoshoujine - 0)
            this.$set(this.formData, 'baseCurAmount', this.xiaoshoujine - 0)

            this.$set(this.formData, 'taxRate', this.formData.taxRate - 0)
            // this.setSelectedInfo(this.formData)
            // // 客户端弹窗预览结果
            // // 参数依次为: 打开页面地址、标题、回调函数
            // openAppClient('/showSelectedData', '选择结果11', function () {
            //     // alert('关闭后回调')
            // })

            await auditRequest.setwzxsjs(this.formData)

            for(let i = 0 ; i < this.wzlbTableData.length ; i++) {
                if(this.wzlbTableData[i].children.length > 0) {
                    for(let j = 0 ; j < this.wzlbTableData[i].children.length; j++) {
                        if(this.wzlbTableData[i].children[j].changeType !== -1) {
                            if(this.wzlbTableData[i].children[j].changeType === null) {
                                this.wzlbTableData[i].children[j].changeType = 2
                            }else{
                                this.wzlbTableData[i].children[j].changeType = 1
                            }
                        }
                        // this.wzlbTableData[i].children[j].billId = data
                        this.wzlbTableData[i].children[j].quantity = this.wzlbTableData[i].children[j].settlementUnit
                    }
                }
            }
            await auditRequest.upadatejsmx(this.wzlbTableData)
            this.clientPop('suc', '保存成功')
            location.reload()
        },
        //选择合同
        xzxsgt () {
            selectDataClient({
                SelectServiceToken: '/subcontract/thirdParty/getSalesSettlement', // 客户端对应方法名
                IsSingleMode: true, // 是否单选 true 单选 false 多选
                SelectedIDs: [], // 已选中id(注意：是上一次已选中的id，不是要传的参数，如果第一次选，则传[])
                InitParamsStr: JSON.stringify({ orgId: this.user.userInfo.orgInfo.orgId }),    // 接口参数(name为模拟参数)
                Title: '选择结算明细' // 标题
            }).then(val => {
                let target = null
                if(val.length > 0) {
                    for(let i = 0 ; i < val.length; i++) {
                        if(val[i].parentId != '0' || val[i].parentId != 0) {
                            target = val[i]
                        }
                    }
                }
                let res = target //默认用户选择了第一个 模拟弹窗
                this.$set(this.formData, 'customerName', res.firstPartyName)
                this.$set(this.formData, 'customerId', res.firstPartyId)
                this.$set(this.formData, 'contractName', res.contractName)
                this.$set(this.formData, 'contractBillNo', res.contractNumber)
                this.$set(this.formData, 'contractBillId', res.contractId)
                this.$set(this.formData, 'currency', res.currencyName)
                this.$set(this.formData, 'currencyId', res.currencyId)
                this.$set(this.formData, 'baseCurName', res.currencyName)
                this.$set(this.formData, 'baseCurId', res.recordId)
                this.$set(this.formData, 'taxRate', res.taxRate)
                res = []
                if(this.wzlbTableData.length > 0 && this.wzlbTableData[0].children.length > 0) {
                    this.wzlbTableData[0].children.forEach(item=>{
                        for(let i = 0 ; i < val.length ; i++) {
                            if(item.contractDtlId != val[i].billId) {
                                if(val[i].parentId != '0' && val[i].parentId != 0) {
                                    res.push(val[i])
                                }
                            }
                        }
                    })
                }else {
                    for(let i = 0 ; i < val.length ; i++) {
                        if(val[i].parentId != '0' && val[i].parentId != 0) {
                            res.push(val[i])
                        }

                    }
                }
                const mapObj = {}
                let arr = []
                res.forEach(e => {
                    const children = []
                    e.materialClassNameArr = e.contractName.split('/')
                    e.materialClassIdArr = e.contractId.split('/')
                    let obj
                    const topClassId = e.materialClassIdArr.splice(0, 1).toString()
                    const topClassName = e.materialClassNameArr.splice(0, 1).toString()
                    if (!mapObj[topClassId]) {
                        obj = {
                            topClassId,
                            topClassName,
                            customId: topClassId,
                            materialClassId: topClassId,
                            materialClassName: topClassName,
                            uuid: getUuid(),
                            totalAmount: null,
                            totalQuantity: null,
                        }
                        //这里需要改成push多个对象   还没改
                        arr.push(obj)

                        mapObj[topClassId] = obj
                    } else {
                        obj = mapObj[topClassId]
                    }
                    children.push({
                        uuid: getUuid(),
                        billId: this.billId || '',
                        billNo: this.basicFormData.billNo || '',
                        customId: getUuid(),
                        warehouse: e.warehouse,
                        unsettledQuantity: e.unsettledQuantity, //未结算数量
                        acceptedQuantity: null, //已验收数量
                        changeType: 1,
                        dtlId: '', //加工收料明细id
                        materialClassId: e.materialClassIdArr.join('/'), //物资类别id(
                        materialClassName: e.materialClassNameArr.join('/'), //物资类别名称
                        materialId: e.listId, //物资id
                        materialName: e.materialName, //物资名称
                        price: 0, //单价
                        quantity: e.surplusQuantity, //数量
                        sourceDtlId: '', //源单明细id
                        spec: e.specificationModel, //规格型号
                        texture: e.textureOfMaterial, //材质
                        unit: e.unit, //计量单位
                        warehouseId: this.warehouse ? this.warehouse.billId : '', //仓库id
                        warehouseName: this.warehouse ? this.warehouse.name : '', //仓库名称
                        settlementUnit: e.unsettledQuantity, //结算数量
                        amount: 0, //金额
                        contractDtlId: e.billId
                    })
                    obj.children = !obj.children
                        ? children
                        : obj.children.concat(children)
                    obj.children = this.uniqueArray(obj.children, 'customId')
                })
                this.wzlbTableData = arr
            })
        },
        gaibian (obj, type) {
            if(type == '数量') {
                if(obj.unsettledQuantity < obj.settlementUnit) {
                    obj.settlementUnit = obj.unsettledQuantity
                    if(obj.amount && obj.settlementUnit) {
                        obj.amount = obj.amount - 0
                        obj.settlementUnit = obj.settlementUnit - 0
                        obj.price = (obj.amount / obj.settlementUnit) - 0
                    }else{
                        obj.price =  0
                    }
                    showErrorPop('结算数量不能超过未结算数量')
                }
                obj.settlementUnit = (Number(obj.settlementUnit) || 0).toFixed(4) * 1
            }
            if(obj.amount && obj.settlementUnit) {
                obj.amount = obj.amount - 0
                obj.settlementUnit = (Number(obj.settlementUnit) || 0).toFixed(4) * 1
                obj.price = (((obj.amount / obj.settlementUnit) - 0).toFixed(2)) - 0
                obj.amount = (Number(obj.amount) || 0).toFixed(2) * 1
            }else{
                obj.price =  0
            }
            //更新税额与税价合计
            this.formData.taxAmount = (this.xiaoshoujine * (this.formData.taxRate / 100)).toFixed(2) * 1
            this.formData.totalAmount = (this.xiaoshoujine + this.formData.taxAmount).toFixed(2) * 1
        },
        //我的方法 ↑
        initData () {
            this.getCurrentUnitInfo()
            this.getTurnoverCentralizedPurchaseSummaryGetAgencyListByBillId()
            this.getBasicData()
            this.getTurnoverCentralizedPurchaseSummaryGetSummarySetting() //回去物资汇总明细
        },

        //根据周材集采汇总id查询申报机构
        getTurnoverCentralizedPurchaseSummaryGetAgencyListByBillId () {
            planRequest.turnoverCentralizedPurchaseSummaryGetAgencyListByBillId(this.billId).then(res=>{
                this.OrgtableData = res
            })
        },

        //根据周材集采汇总id查询申报机构
        getTurnoverCentralizedPurchaseSummaryGetSummarySetting () {
            planRequest.turnoverCentralizedPurchaseSummaryGetSummarySetting(this.billId).then(res=>{
                console.log(res, '当前打印')
                // this.OrgtableData = res
                this.notSetData = JSON.parse(JSON.stringify(res)) //没去重之前的数据
                //去重
                let children = []
                res.forEach(item=>{
                    item.children.forEach(a=>{
                        children.push(a)
                    })
                })
                var result = []
                var obj = {}
                for (var i = 0; i < children.length; i++) {
                    if ( children[i].materialId in obj) {
                        // 相同时肯定不push
                        if (obj[children[i].materialId] !== children[i].texture) {
                            // 不相同时，判断是否是 '' 和 null，如果是，则表示重复
                            if (!(!obj[children[i].materialId] && !children[i].texture)) {
                                // 当都不是 '' 和 null 时，才表示不重复，此时才push
                                result.push(children[i])
                            }
                        }
                    } else {
                        obj[children[i].materialId] = children[i].texture
                        result.push(children[i])
                    }
                    // obj[children[i].amount] = 1

                }
                res.forEach(item=>{
                    item.uuid = getUuid()

                    item.materialClassName = item.topClassName
                    item.children = result
                    item.children.forEach(v=>{
                        v.uuid = getUuid()
                        v.parentId = item.uuid
                    })
                })
                console.log(result, 'datadata')
                this.materialsTableData = res
            })
        },

        uniqueArray (arr, key) {
            const map = new Map()
            return arr.filter(item => {
                const val = item[key] + '' || getUuid()
                return !map.has(val) && map.set(val, 1)
            })
        },

        /**
         * 下边几个按钮
         */
        //保存按钮
        submit () {
            this.$refs['basicFormData'].validate(valid => {
                if (valid) {
                    const data = JSON.parse(JSON.stringify(this.OrgtableData))

                    // 明细非空验证
                    this.verifyTable()
                    if (this.isErrorMsg) {
                        return
                    }
                    return new Promise((resolve, reject)=>{

                        planRequest.turnoverCentralizedPurchaseSummaryUpdateDtlList(data).then(res=>{
                            resolve(res)
                            showSuccessPop('保存明细成功！', this.initData)
                        }).catch(err=>{
                            reject(err)
                        })
                        if(this.isCollect) { //初次进入页面 点击了申报单位之后的回调s
                            const resource = []
                            data.forEach(item=>{
                                if(item.dtls) {
                                    item.dtls.forEach(v=>{
                                        v.children.forEach(n=>{
                                            n.billId = this.billId
                                        })
                                        resource.push(v)
                                    })
                                }

                            })
                            planRequest.turnoverCentralizedPurchaseSummarySaveSummarySetting(resource).then(res=>{
                                resolve(res)
                                showSuccessPop('保存物资汇总成功！', this.initData)
                            }).catch(err=>{
                                reject(err)
                            })
                        }
                        //修改基础信息
                        planRequest.turnoverCentralizedPurchaseSummaryUpdate(this.basicFormData).then(res => {
                            resolve(res)
                            showSuccessPop('保存基础成功！', this.initData)
                        }).catch(err=>{
                            reject(err)
                        })
                    })

                }
            })
        },

        // 保存并提交
        submitCommit () {
            this.$refs.rulesBase.validate(valid => {
                console.log('gg', valid)
                if (valid) {
                    this.tijiao111()
                } else {
                    console.log('error submit!!')
                    return false
                }
            })
        },
        async tijiao111 () {
            if(this.formData.customerName == '' || !this.formData.customerName) {
                this.clientPop('err', '请选销售合同')
                return
            }

            //点击详情进来的
            this.$set(this.formData, 'amount', this.xiaoshoujine)
            this.$set(this.formData, 'baseCurAmount', this.xiaoshoujine)
            this.$set(this.formData, 'taxRate', this.formData.taxRate - 0)

            await auditRequest.setwzxsjs(this.formData)

            for(let i = 0 ; i < this.wzlbTableData.length ; i++) {
                if(this.wzlbTableData[i].children.length > 0) {
                    for(let j = 0 ; j < this.wzlbTableData[i].children.length; j++) {
                        if(this.wzlbTableData[i].children[j].changeType !== -1) {
                            if(this.wzlbTableData[i].children[j].changeType === null) {
                                this.wzlbTableData[i].children[j].changeType = 2
                            }else{
                                this.wzlbTableData[i].children[j].changeType = 1
                            }
                        }
                        // this.wzlbTableData[i].children[j].billId = data
                        this.wzlbTableData[i].children[j].quantity = this.wzlbTableData[i].children[j].settlementUnit
                    }
                }
            }
            await auditRequest.upadatejsmx(this.wzlbTableData)

            await publicReques.commitexamine({ billId: this.billId,	billType: '1021' })
            this.clientPop('suc', '提交审核成功')
            this.$router.replace('/salesSettlementlist')
        },
        //计划明细非空验证
        verifyTable () {

            this.errorMsg = []
            if(this.OrgtableData.length > 0) {
                this.OrgtableData.forEach((n, index)=>{
                    if(n.dtls) {
                        n.dtls.forEach(v=>{
                            v.children.forEach(item=>{
                                if(item.changeType !== -1) {
                                    if (item.approvalQuantity == '' || item.approvalQuantity == null) {
                                        let str = `请填写第 ${index + 1} 行的核准数量`
                                        this.errorMsg.push(str)
                                    }
                                    if (item.approvalPrice == '' || item.approvalPrice == null) {
                                        let str = `请填写第 ${index + 1} 行的核准单价`
                                        this.errorMsg.push(str)
                                    }

                                }
                            })
                        })
                    }

                })
            }

            if(this.errorMsg.length > 0) {
                this.isErrorMsg = true

            }else{
                this.isErrorMsg = false

            }
        },
        async nullify () {
            //撤回
            console.log('撤回')
            await publicReques.goBack({ billId: this.billId, billType: '1021' })
            this.clientPop('suc', '撤回成功')
            this.$router.replace('/salesSettlementlist')
        },
        zuofei () {
            this.setAuditParams(this.nullifyParams)
            // 客户端弹窗弹出本地页面
            openAppClient('/nullifyDialog', '单据作废原因', () => {
                const auditParams = JSON.parse(localStorage.vuex).auditParams
                publicReques.zuofei(auditParams)
                    .then(() => {
                        this.clientPop('suc', '作废成功', this.handleClose)
                    })

            })
        },

        // 汇总逻辑
        count_ (row, num) {
            row.changeType = num
            this.basicFormData.amount = null

            row.approvalAmount =  row.approvalQuantity * row.approvalPrice
            this.OrgtableData.forEach(item =>{
                console.log(item, '逻辑汇总')
                item.changeType = num
                this.basicFormData.amount += item.totalAmount = row.approvalAmount  //把汇总的金额给父级 方便汇总计算
                if(item.children) {
                    item.children.forEach(i=>{
                        i.changeType = num
                    })
                }
            })
        },
        // 删除明细 tps
        deleteEle (row) {
            this.clientPop('info', '是否删除数据？', ()=>{
                this.wzlbTableData[0].children.forEach((item, index)=>{
                    if(item.contractDtlId == row.contractDtlId) {
                    //如果当前选中的是新增数据只需要把从数组中删除即可
                        if(row.changeType != 1) {
                            const copy = JSON.parse(JSON.stringify(this.wzlbTableData[0].children[index]))
                            copy.changeType = -1
                            const paramList = [
                                {
                                    'children': [copy],
                                    'topClassId': '',
                                    'topClassName': '',
                                    'totalAmount': 0,
                                    'totalQuantity': 0,
                                }
                            ]
                            auditRequest.upadatejsmx(paramList)
                        }
                        this.wzlbTableData[0].children.splice(index, 1)
                        if(this.wzlbTableData[0].children.length == 0) {
                            this.wzlbTableData = [
                                {
                                    'children': [],
                                    'topClassId': '',
                                    'topClassName': '',
                                    'totalAmount': 0,
                                    'totalQuantity': 0,
                                    'uuid': getUuid()
                                }
                            ]
                        }
                        return
                    }
                })
                console.log(this.xiaoshoujine, 'this.xiaoshoujine')
                //更新税额与税价合计
                this.formData.taxAmount = (this.xiaoshoujine * (this.formData.taxRate / 100)).toFixed(2) * 1
                this.formData.totalAmount = (this.xiaoshoujine + this.formData.taxAmount).toFixed(2) * 1
            })
        },
        //获取集采汇总id获取基本信息
        getBasicData () {
            planRequest.turnoverCentralizedPurchaseSummaryFindById(this.billId)
                .then(res => {
                    this.basicFormData = res
                })
        },
        //获取所属机构下的仓库
        getProjectDepartmentWarehouse () {
            auditRequest.getProjectDepartmentWarehouse({ orgId: this.user.userInfo.orgInfo.orgId })
                .then(res=>{
                    this.warehouse = res
                })
        },

        //申报机构删除逻辑
        tableRowClassName ({ row }) {
            if (row.changeType === -1) {
                return 'warning-row'
            }
            return ''
        },
        //取消
        handleClose () {
            // this.dialogVisible = false
            this.$router.replace('/salesSettlementlist')
        },
        onChangeTab (e) {
            const height  = $('#' + e.name).offset().top
            $.scrollTo(height - this.topHeight, 500)
            // 如果手动点击时，则不做滚动事件逻辑，只有滚动屏幕时才走滚动事件逻辑
            this.clickTabFlag = true
            // 动画结束后，恢复状态
            setTimeout(() => {
                this.clickTabFlag = false
            }, 600)
        },
        // 获取最后一个内容区域的高度，计算底部空白
        getLastConHeight () {
            let si = setInterval(() => {
                // 因为dom异步加载，通过轮询找到渲染后的dom，获取高度
                if (document.getElementById('evaluateCon')) {
                    const lastConHeight =
            document.getElementById('evaluateCon').offsetHeight
                    console.log('lastConHeight: ', lastConHeight)
                    this.lastConHeight = lastConHeight
                    console.log('this.lastConHeight', this.lastConHeight)
                    clearInterval(si)
                    si = null
                }
            }, 100)
        },
        cellClsNm ({ column }) {
            if (column.label === '') {
                return 'fixed-left'
            }
        },
        //税率事件
        taxRateEvent (val) {
            if(0 <= val && val <= 100) {
                this.formData.taxRate = Number(val).toFixed(2) * 1
            }else{
                this.$message.error('税率填写范围为0~100之间')
                this.formData.taxRate = 0
            }
            //更新税额与税价合计
            this.formData.taxAmount = (this.xiaoshoujine * (this.formData.taxRate / 100)).toFixed(2) * 1
            this.formData.totalAmount = (this.xiaoshoujine + this.formData.taxAmount).toFixed(2) * 1
        },
        //税额事件
        taxAmountEvent (val) {
            this.formData.taxAmount = Number(val).toFixed(2) * 1
            //更新税价合计
            this.formData.totalAmount = (this.xiaoshoujine + this.formData.taxAmount).toFixed(2) * 1
        },
        //查看源单
        goTocontract () {
            openAppClient(
                `/ctMaterialSalesApplyShow?billid=${this.formData.contractBillId}&isview=true`, '查看物资销售合同'
            )
        }
    },
}
</script>

<style lang="scss" scoped>
.buttons {
  left: 0;
}
.e-form {
  margin-bottom: 80px;
  padding: 0 20px;
  .tabs-title::before {
    content: "";
    height: 22px;
    width: 8px;
    border-radius: 40px;
    background-color: #2e61d7;
    display: block;
    position: absolute;
    left: 20px;
    margin-right: 20px;
  }
}
.right_{
    float: right;
}
.e-table {
  background: #fff;
}
::v-deep.el-table .warning-row {
  display: none;
}
// ::v-deep.el-table__body-wrapper::-webkit-scrollbar{
//      width: 6px !important; // 横向滚动条
//     height: 10px !important// 纵向滚动条
// }

::v-deep .el-table__body-wrapper::-webkit-scrollbar {
  width: 6px; // 横向滚动条
  height: 10px; // 纵向滚动条
}
// 滚动条的滑块
::v-deep .el-table__body-wrapper::-webkit-scrollbar-thumb {
  background-color: #ddd;
  border-radius: 5px;
}

.el-tab-pane {
  margin-left: -10px;
}
.childTab {
  ::v-deep .el-tabs__header {
    position: absolute !important;
  }
  ::v-deep .el-tabs__content {
    padding: 0 0 0 20px !important;
  }
}
.childTab1 {
  ::v-deep .el-tabs__header {
    position: absolute !important;
    .el-tabs__nav-scroll {
      position: relative;
      .el-tabs__nav {
        position: fixed;
        top: 0;
        width: 190px;
      }
    }
  }
}
.childTab2 {
  ::v-deep .el-tabs__header {
    position: absolute !important;
    .el-tabs__nav-scroll {
      position: relative;
      .el-tabs__nav {
        position: absolute;
        bottom: 0;
        width: 100%;
      }
    }
  }
}
</style>
